package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"hr/config"
	"log"
	"os"
	"time"
)

var gormDb *gorm.DB

// Open 打开数据库
func Open() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,         // 禁用彩色打印
		},
	)
	mysqlConfig := config.AppConfig.Db
	template := "%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf(template, mysqlConfig.Username, mysqlConfig.Password, mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.DbName)
	openDb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		log.Println(err.Error())
		panic("数据库连接异常")
	}
	fmt.Println(fmt.Sprintf("*********************数据库连接成功*********************%s", config.AppConfig.Db.Host))
	gormDb = openDb


	autoMigrate(&User{}, &Role{}, &Menu{}, &Dict{}, &DictValue{}, &Dept{}, &Post{},&ClothingApproval{},&ExpenseDeclarationApproval{},&FormalApproval{},&InsureApproval{},&NoInsureApproval{},&OfficialSealApproval{},&PostTransferApproval{},&QuitApproval{},&WorkOvertimeApproval{}, &AdMenage{}, &ApplicationManage{}, &AttendanceManage{}, &CompanyProfile{}, &FileManage{}, &InviteManage{}, &PublicityManage{}, &RecruitmentManage{}, &ServicePublicity{}, &UserManage{}, &WorkflowRecord{}, &BannerMenage{}, &TabsMenage{})
}

// Close 关闭数据库
func Close() {
	sqlDB, _ := gormDb.DB()
	sqlDB.Close()
	gormDb = nil
}

// GetInstance 获取数据库实例
func GetInstance() *gorm.DB {
	return gormDb
}

func autoMigrate(values ...interface{}) {
	if err := gormDb.AutoMigrate(values...); err != nil {
		fmt.Println("数据库表生成失败")
	}
	fmt.Println("*********************数据库表生成成功*********************")
}

type AppModel struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
